package com.zhihuishu.micro.course.openapi.course.impl;

import com.zhihuishu.micro.course.dto.CourseDataDto;
import com.zhihuishu.micro.course.dto.CourseFolderDto;
import com.zhihuishu.micro.course.dto.CourseFolderRootAndDirDto;
import com.zhihuishu.micro.course.dto.LessonVideoDto;
import com.zhihuishu.micro.course.openapi.course.CCFolderOpenService;
import com.zhihuishu.micro.course.openapi.course.CourseLessonVideoOpenService;
import com.zhihuishu.micro.course.openapi.course.dto.CourseLessonVideoDto;
import com.zhihuishu.micro.course.service.CCDataTreenityDBService;
import com.zhihuishu.micro.course.service.CCDataTreenityService;
import com.zhihuishu.micro.course.service.CCFolderTreenityService;
import com.zhihuishu.micro.course.service.LessonVideoTreenityService;
import com.zhihuishu.remote.ErrorCode;
import com.zhihuishu.remote.RemoteException;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Jiangli
 * @date 2016/10/17 15:27
 */
@Service("courseLessonVideoOpenService")
public class CourseLessonVideoOpenServiceImpl extends BaseOpenImpl implements CourseLessonVideoOpenService {
    @Resource
    private LessonVideoTreenityService lessonVideoAllService;//所有小节 service

    @Resource
    private CCFolderTreenityService ccFolderTreenityService;
    @Resource
    private CCDataTreenityService ccDataTreenityService;
    @Resource
    private CCDataTreenityDBService ccDataTreenityServiceDB;

    @Resource
    private CCFolderOpenService courseFolderOpenService;

    private static final String moduleNameCN = "小节";

    @Override
    public RemoteResult<CourseLessonVideoDto> createByDto(CourseLessonVideoDto courseChapterDto, long createUserId) throws RemoteException {
        return createByDto(courseChapterDto,true,createUserId);
    }

    @Override
    public RemoteResult<CourseLessonVideoDto> createByDto(CourseLessonVideoDto courseChapterDto, Boolean createData, long createUserId) throws RemoteException {
        RemoteResult<CourseLessonVideoDto> result = new RemoteResult<CourseLessonVideoDto>();
        try {
            //如果有dataId  需要通过dataId查询最新数据
            //并且转化为CourseLessonVideo存储
            Integer dataId = courseChapterDto.getDataId();
            if (!StringUtils.isEmpty(dataId)) {
                CourseDataDto detail = ccDataTreenityServiceDB.detail(dataId);
                //convert CourseDataDto -> CourseLessonVideoDto
                courseChapterDto.setVideoImg(detail.getThumbnailUrl());
                if (detail.getVideoSize() != null) {
                    courseChapterDto.setVideoSec(Long.parseLong(detail.getVideoSize()));
                }

                courseChapterDto.setFileName(detail.getName());
            }

            LessonVideoDto dbDto = BeanHelper.transTo(courseChapterDto, LessonVideoDto.class);

            Integer newId = lessonVideoAllService.create(dbDto, createUserId);
            dbDto.setId(newId);

            CourseLessonVideoDto resultDto = BeanHelper.transTo(dbDto, CourseLessonVideoDto.class);

            result.setSuccess(true);
            result.setResult(resultDto);


            //若为本地上传版的-上传、替换
            //则添加data数据
            final  Long courseId = resultDto.getCourseId();
            //找到course下root文件夹下的Course Videos文件夹，并且插入一条data数据
            if (courseId != null && createData != null && createData) {
                final String specialFolderName = "Course Videos";

                //1.courseId -> get rootId, [Course Videos] dirId
                CourseFolderRootAndDirDto rootAndDir = ccFolderTreenityService.findRootAndDir(courseId, specialFolderName);

                //2.[Course Videos] dirId is null -> create CC_FOLDER -> get [Course Videos] dirId
                Integer speDirId = rootAndDir.getSpeDirId();
                if(rootAndDir.getRootDirId() != null){
                    if(speDirId == null){
                        log.debug("should create a folder for course[{}]-folder[{}]",courseId,specialFolderName);
                        CourseFolderDto dto = new CourseFolderDto();
                        dto.setCourseId(courseId);
                        dto.setParentId(rootAndDir.getRootDirId().longValue());
                        dto.setName(specialFolderName);
                        dto.setPrivilege(1);
                        Integer genId = ccFolderTreenityService.create(dto, createUserId);

                        speDirId = genId;
                    } else {
                        //update privilege to   Teacher Only ie.1
                        //auto update to 1
                        Integer dbPri = rootAndDir.getPrivilege();
                        if (dbPri == null || dbPri != 1) {
                            courseFolderOpenService.updatePrivilageForAllChildren(Arrays.asList(speDirId), null, 1, createUserId);

//                            CourseFolderDto dto = new CourseFolderDto();
//                            dto.setPrivilege(1);
//                            dto.setId(speDirId);
//                            ccFolderTreenityService.update(dto,createUserId);
                        }
                    }
                }


                //3.[Course Videos] dirId  -> create DATA
                if(speDirId != null){
                    try {
                        //convert CourseLessonVideoDto -> CourseDataDto
                        CourseDataDto dto = new CourseDataDto();
                        dto.setInterfaceDataId(courseChapterDto.getVideoId().intValue());
                        dto.setDataType("3");
                        dto.setUrl(courseChapterDto.getVideoUrl());
                        dto.setFolderId(speDirId.longValue());
                        dto.setPrivilege(1);//仅老师可见
                        if(courseChapterDto.getFileSize() != null)
                            dto.setSize(courseChapterDto.getFileSize().longValue());
                        String fileName = courseChapterDto.getFileName();
                        if (fileName != null) {
                            dto.setName(fileName);
                            String suffix = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
                            dto.setSuffix(suffix);
                        }

                        //save
                        ccDataTreenityService.create(dto, createUserId);
                    } catch (Exception e) {
                        log.error("插入文件数据-" + moduleNameCN + "-报错",e);
                    }
                } else {
                    log.error("no folderId for course[{}]-folder[{}]",courseId,specialFolderName);
                }
            }
        } catch (Exception e) {
            log.error("保存-" + moduleNameCN + "-报错",e);
            throw new RemoteException(e).setMessage("保存-" + moduleNameCN + "-报错!");
        }

        return result;
    }

    @Override
    public RemoteResult<Void> updateByDto(CourseLessonVideoDto chapter, long updateUserId) throws RemoteException {
        RemoteResult<Void> result=new RemoteResult<Void>();
        if(chapter==null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
            return result;
        }
        try {
            LessonVideoDto chapterDto = BeanHelper.transTo(chapter, LessonVideoDto.class);
            lessonVideoAllService.update(chapterDto,updateUserId);

            result.setSuccess(true);
        } catch (Exception e) {
            throw new RemoteException(e).setMessage("修改-" + moduleNameCN + "-出错!") ;
        }
        return result;
    }

    @Override
    public RemoteResult<Void> deleteById(Integer chapterId, long deleteUserId) throws RemoteException {
        RemoteResult<Void>  result = new RemoteResult<Void>();
        if(chapterId == null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
            return result ;
        }
        try {
            lessonVideoAllService.delete(chapterId,deleteUserId);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RemoteException(e).setMessage("删除-" + moduleNameCN + "-出错!") ;
        }
        return result;
    }

    @Override
    public RemoteResult<List<CourseLessonVideoDto>> queryListByCourseId(long courseId) throws RemoteException {
        RemoteResult<List<CourseLessonVideoDto>> result=new RemoteResult<List<CourseLessonVideoDto>>();
        try {
            List<LessonVideoDto> chapterDtoList = lessonVideoAllService.list(courseId);
            List<CourseLessonVideoDto> courseOpenDtoList =  new ArrayList<CourseLessonVideoDto>();
            if (!CollectionUtils.isEmpty(chapterDtoList)){
                for(LessonVideoDto course : chapterDtoList){
                    CourseLessonVideoDto courseOpenDto = BeanHelper.transTo(course, CourseLessonVideoDto.class);
                    courseOpenDtoList.add(courseOpenDto);
                }
            }
            result.setResult(courseOpenDtoList);
        } catch (Exception e) {
            result.setSuccess(false);
            throw new RemoteException(e).setMessage("查询-" + moduleNameCN + "列表-出错!") ;
        }
        return result;
    }

    @Override
    public RemoteResult<CourseLessonVideoDto> queryDetailByLvId(int lvId) throws RemoteException {
        RemoteResult<CourseLessonVideoDto> result=new RemoteResult<CourseLessonVideoDto>();
        try {
            LessonVideoDto lessonVideoDto = lessonVideoAllService.detail(lvId);

            if (lessonVideoDto != null) {
                CourseLessonVideoDto courseOpenDto = BeanHelper.transTo(lessonVideoDto, CourseLessonVideoDto.class);
                result.setResult(courseOpenDto);
            }
        } catch (Exception e) {
            result.setSuccess(false);
            throw new RemoteException(e).setMessage("查询-" + moduleNameCN + "详情-出错!") ;
        }
        return result;
    }

    @Override
    public RemoteResult<Void> sortByDtoList(List<CourseLessonVideoDto> chapterList, long updateUserId) throws RemoteException {
        RemoteResult<Void> result=new RemoteResult<Void>();
        if(CollectionUtils.isEmpty(chapterList)){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
            return result;
        }
        try {
            List<LessonVideoDto> dbDtoList = new LinkedList<LessonVideoDto>();
            for (CourseLessonVideoDto courseChapterDto : chapterList) {
                dbDtoList.add(BeanHelper.transTo(courseChapterDto, LessonVideoDto.class));
            }

            lessonVideoAllService.sort(dbDtoList,updateUserId);

            result.setSuccess(true);
        } catch (Exception e) {
            throw new RemoteException(e).setMessage("排序-" + moduleNameCN + "-出错!") ;
        }
        return result;
    }

    @Override
    public RemoteResult<Void> updateVideoIdRedis(Integer videoId, Integer lessonId, Integer lesssonVideoId) {
        RemoteResult<Void> remoteResult=new RemoteResult<Void>();
        try {
            Assert.isNull(videoId, "视频id不能为null");
            Assert.isNull(lesssonVideoId, "小节id不能为null");
            lessonVideoAllService.updateVideoIdRedis(videoId,lessonId,lesssonVideoId);
        } catch (Exception e) {
            remoteResult.setSuccess(false);
            remoteResult.setExceptionStack(e);
        }
        return remoteResult;
    }
}
